package com.xgry.bpm.config.datasouce.oldsource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xgry.bpm.api.base.dbinfo.service.DbinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DataDBServer {

    @Autowired
    private JdbcTemplate basejdbc;

    private JdbcTemplate jdbcTemplate;
    private Map DataMap=new HashMap();

    public JdbcTemplate getJdbcTemplate(int id){
        return basejdbc;
    }

    /**
     * 原bpm切换库所使用jdbcTemplate，现在统一切换为yml配置的主库进行操作。
     * @param id
     * @return
     * @throws Exception
     */
    @Deprecated
    public JdbcTemplate getJdbcTemplate_old(int id)throws Exception{
        jdbcTemplate=(JdbcTemplate)DataMap.get(id);
        if(jdbcTemplate==null){
            List<Map<String, Object>> maps = basejdbc.queryForList("select * from dbinfo where id="+id);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(maps));

            if(jsonArray!=null && jsonArray.size()>0){
                JSONObject dbinfo=jsonArray.getJSONObject(0);
                DruidDataSource ds = new DruidDataSource();
                ds.setUrl("jdbc:sqlserver://"+dbinfo.getString("cServer")+":"+dbinfo.getString("cPost")+";DatabaseName="+dbinfo.getString("cDBName")+"");
                ds.setUsername(dbinfo.getString("cUser"));
                ds.setPassword(dbinfo.getString("cPassWord"));
                switch (dbinfo.getString("cType")){
                    case "MSSQL":
                        ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                        break;
                    case "ORACEL":
                        ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                        break;
                    case "MYSQL":
                        ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                        break;
                }
                ds.setMaxActive(10);
                ds.setTimeBetweenEvictionRunsMillis(300000);
                ds.setQueryTimeout(30);
                ds.init();
                DataSource createDataSource = (DataSource) ds;
                jdbcTemplate = new JdbcTemplate();
                jdbcTemplate.setDataSource(createDataSource);
                DataMap.put(id,jdbcTemplate);

            }
        }
        return jdbcTemplate;
    }
}
